#include "yhservice.h"
#include "yhargs.h"
#include "yhevent.h"
#include "yhsocket.h"
#include "yherror.h"

#include "iokeyboard.h"
#include "ioudp.h"
#include "iotcp.h"

char * ip;
char * domain_socket_path = (char*)"/var/tmp/daemon";

void before(const em_t * const em)
{
    log_msg("before");
}

void event(const em_t * const em, int ret)
{
    log_msg("epoll_wait ret %d", ret);
    if (ret < 0) {
        if (errno == EAGAIN || errno == EINTR) return;
        err_msg("epoll_wait error %d: %s", errno, strerror(errno));
        exit(1);
    }
}

void after(const em_t * const em)
{
    log_msg("after");
}

void service_create()
{
    //em_t *em = em_open(999, 1000, before, event, after);
    em_t *em = Em_open(999, -1, 0, 0, 0);
    Em_run(em, 1);

    if (local)
        ip = (char*)"127.0.0.1";
    else
        ip = (char*)"0.0.0.0";

    // demo 1: network server tcp
    int tcpsfd = create_server_tcp4(ip, port, 1000);
    if (tcpsfd < 0) {
        err_sys("create_tcp_v4_server %s:%d error", ip, port);
    }
    log_msg("tcp fd %d server - %s:%d", tcpsfd, ip, port);
    fe_t * festcp = Fe_new(em, tcpsfd);
    fe_set(festcp, EPOLLIN, tcp_server);
    fe_set(festcp, EPOLLET, 0);
    setfd_nonblock(tcpsfd);
    fe_em_add(festcp);

    // demo 2: network server udp
    int udpsfd = create_server_udp4(ip, port, 1000);
    if (udpsfd < 0) {
        err_sys("create_udp_v4_server %s:%d error", ip, port);
    }
    log_msg("udp fd %d server - %s:%d", udpsfd, ip, port);
    fe_t* fesudp = Fe_new(em, udpsfd);
    fe_set(fesudp, EPOLLIN, udp_server);
    fe_em_add(fesudp);

    // demo 3: standard input; daemon mode invalid
    if (daemond == 0) {
        fe_t * pin = Fe_new(em, 0);
        setfd_nonblock(0);
        fe_set(pin, EPOLLET, 0);
        fe_set(pin, EPOLLIN, _stdin_);
        //fe_unset(pin, EPOLLIN); // unset test ok
        fe_em_add(pin);
    }

    // demo4: unix domain socket server
    int domainfd = unix_domain_server_tcp(domain_socket_path);
    if (domainfd < 0) {
        err_sys("unix_domain_listen %s error", domain_socket_path);
    }
    log_msg("dms fd %d server - %s", domainfd, domain_socket_path);
    fe_t * fedomain = Fe_new(em, domainfd);
    fe_set(fedomain, EPOLLIN, domain_server);
    fe_set(fedomain, EPOLLET, 0);
    setfd_nonblock(domainfd);
    fe_em_add(fedomain);
}
